/**
 * 
 */
package com.uyayo.framework.web.resolver;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * @author Michael 2017年5月25日 下午8:13:59
 * @since 1.0
 * @see
 */
public class DefaultHandlerExceptionResolver implements HandlerExceptionResolver {

	private Logger logger = LoggerFactory.getLogger(getClass());
	private final static String ERR_CODE = "RA-9000";
	private final static String VIEW_NAME = "500";
	/* (non-Javadoc)
	 * @see org.springframework.web.servlet.HandlerExceptionResolver#resolveException(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
		// TODO Auto-generated method stub
		logger.error("系统拦截的异常", ex);
		
		ModelAndView modelAndView = new ModelAndView();
		if (isJsonRequest(request)) {
			FastJsonJsonView jsonView = new FastJsonJsonView();
			HashMap<String, String> attributes = new HashMap<String, String>();
			attributes.put("customer.error.message", ERR_CODE);
			jsonView.setAttributesMap(attributes);
			modelAndView.setView(jsonView);
		}else{
			modelAndView.setViewName(VIEW_NAME);
			modelAndView.addObject("customer.error.message", ERR_CODE);
		}
		return modelAndView;
	}
	
	/**
     * 是否是Json请求
     * 
     * @param request Http请求
     * @return 是则返回<code>TRUE</code>
     */
    public final boolean isJsonRequest(HttpServletRequest request) {
        String requestedWith = request.getHeader("X-Requested-With");
        if (StringUtils.equalsIgnoreCase(requestedWith, "XMLHttpRequest")) {
            return true;
        }

        String requestUri = request.getRequestURI();
        if (StringUtils.endsWithIgnoreCase(requestUri, ".json")
            || StringUtils.endsWithIgnoreCase(requestUri, ".jsonp")) {
            return true;
        }

        return false;
    }

}
